﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace KLY.Tools.Helper
{
    public static class XMLHelper
    {
        #region Api

        public static T XmlDeserialize<T>(string str) 
            where T : class
        {
            XmlSerializer mySerializer = new XmlSerializer(typeof(T));
            StreamReader mem2 = new StreamReader(
                    new MemoryStream(System.Text.Encoding.UTF8.GetBytes(str)),
                    System.Text.Encoding.UTF8);

            return (T)mySerializer.Deserialize(mem2);
        }

        public static string XmlSerialize(object ObjectToSerialize)
        {
            string result = null;
            try
            {
                XmlSerializer xmlSerializer = new XmlSerializer(ObjectToSerialize.GetType());

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, new UTF8Encoding(false));
                    xmlTextWriter.Formatting = Formatting.Indented;
                    xmlSerializer.Serialize(xmlTextWriter, ObjectToSerialize);
                    xmlTextWriter.Flush();
                    xmlTextWriter.Close();
                    UTF8Encoding uTF8Encoding = new UTF8Encoding(false, true);
                    result = uTF8Encoding.GetString(memoryStream.ToArray());
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLogError("Couldn't Serialize Object:" + ObjectToSerialize.GetType().Name, ex);
            }
            return result;
        }

        #endregion
    }
}
